package com.smart.thrift.config.server;

import com.smart.thrift.model.common.ThriftServiceSignature;
import com.smart.thrift.thriftapi.BasicService;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Proxy;

@Slf4j
@Getter
@Setter
public class ThriftServerFactoryBean implements FactoryBean<BasicService.Iface>, InitializingBean {

    private String beanFactoryName;
    private String beanName;
    private Class<?> beanClass;
    private String beanClassName;
    private Class<?> ifaceClass = BasicService.Iface.class;

    private ThriftServiceSignature serviceSignature;
    private ApplicationContext applicationContext;

    @Override
    public BasicService.Iface getObject() throws Exception {
        log.info("Prepare to generate JDK proxy for {}", beanClass.getName());
        ThriftServerInvocationHandler invocationHandler = new ThriftServerInvocationHandler(applicationContext, beanClass, ifaceClass, serviceSignature);
        return (BasicService.Iface) Proxy.newProxyInstance(ifaceClass.getClassLoader(), new Class[]{ifaceClass}, invocationHandler);
    }

    @Override
    public Class<?> getObjectType() {
        return ifaceClass;
    }


    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("Succeed to instantiate an instance of ThriftClientFactoryBean: {}", this);
    }

}
